package com.lanbu.web.controller.task;


import com.lanbu.system.domain.camera.CaCamera;
import com.lanbu.system.service.ICaCameraService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.List;

@Component("PingTask")
public class PingTask {

    @Autowired
    private ICaCameraService caCameraService;
    @Value("${hikvision.timeout}")
    private int timeout;

    @Scheduled(cron = "0 0/2 * * * ?")
    public void ryNoParams() {
        List<CaCamera> list = caCameraService.selectCaCameraListPing();

        for (CaCamera caCamera : list) {

            Socket socket = null;
            try {
                // 创建 Socket 对象
                socket = new Socket();
                // 创建 SocketAddress 对象，指定目标 IP 地址和端口
                SocketAddress socketAddress = new InetSocketAddress(caCamera.getCameraIp(), Integer.parseInt(caCamera.getCameraPort()));
                // 尝试连接到目标地址和端口，设置超时时间
                socket.connect(socketAddress, timeout);

                caCamera.setCameraStatus("0");
                System.out.println("成功");

            } catch (java.net.SocketTimeoutException e) {

                caCamera.setCameraStatus("1");
            } catch (java.net.ConnectException e) {

                caCamera.setCameraStatus("1");
                return;
            } catch (Exception e) {
                caCamera.setCameraStatus("1");
                //System.out.println("Error checking " + ip + ":" + port + ": " + e.getMessage());
                return ; // 其他异常
            } finally {
                caCameraService.updateCaCamera(caCamera);

                if (socket != null) {
                    try {
                        socket.close(); // 关闭 Socket 连接，释放资源
                    } catch (java.io.IOException e) {
                        System.out.println("Error closing socket: " + e.getMessage());
                    }
                }
            }

        }

    }

}
